﻿using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.OAuth;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using System.Reflection;
using Autofac.Integration.Mvc;
using System.Web.Mvc;
using SIG.Service.Identity;

[assembly: OwinStartup(typeof(SIG.WebMVC.Startup))]
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace SIG.WebMVC
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            //enable cors origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
          

            HttpConfiguration config = new HttpConfiguration();

            var builder = new ContainerBuilder();

            // REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule(new IoCConfig());

            // BUILD THE CONTAINER
            var container = builder.Build();
            // REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);


            app.UseAutofacMiddleware(container);
            // 一定要在 app.UseAutofacMiddleware 之后，才可以注入，在app.UseWebApi之前，不会报错
            ConfigureOAuth(app);

            //  app.UseAutofacLifetimeScopeInjector(container);
            app.UseAutofacWebApi(config);

            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            WebApiConfig.Register(config);            

            app.UseWebApi(config);

           


        }


        public void ConfigureOAuth(IAppBuilder app)
        {

            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SigAuthorizationServerProvider()
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());           

        }


    }
}
